<template>
    <transition appear name="slide">
        <music-list
            :title="title"
            :bg-image="bgImage"
            :songs="songs"
            :isLoadError="isLoadErr"
            @loadRefresh="refreshDate"
        ></music-list>
    </transition>
</template>

<script type="text/ecmascript-6">
    import MusicList from 'components/music-list/music-list'
    import { getSongList } from 'api/recommend'
    import { createSong, isValidMusic, processSongsUrl } from 'common/js/classes/song'
    import { ERR_OK } from 'api/config'
    import { mapGetters } from 'vuex'

    export default {
        name: 'disc',
        data() {
            return {
                songs: [],
                isLoadErr: false
            }
        },
        created() {
            this._getSongList()
        },
        computed: {
            title() {
                return this.disc.dissname
            },
            bgImage() {
                return this.disc.imgurl
            },
            ...mapGetters([
                'disc'
            ])
        },
        methods: {
            _getSongList() {
                if (!this.disc.dissid) {
                    // 回退到推荐页面
                    this.$router.push('/recommend')
                    return
                }
                getSongList(this.disc.dissid).then((res) => {
                    if (res.code === ERR_OK) {
                        processSongsUrl(this._normalizeSongs(res.cdlist[0].songlist))
                            .then((songs) => {
                                this.songs = songs
                            }).catch((err) => {
                                console.log(err)
                                this.isLoadErr = true
                            })
                    }
                })
            },
            _normalizeSongs(list) {
                let ret = []
                list.forEach((musicData) => {
                    if (isValidMusic(musicData)) {
                        ret.push(createSong(musicData))
                    }
                })
                return ret
            },
            refreshDate() {
                this.isLoadErr = false
                this._getSongList()
            }
        },
        components: {
            MusicList
        }
    }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
    .slide-enter-active, .slide-leave-active
        transition: all .3s

    .slide-enter, .slide-leave-to
        transform: translate3d(100%, 0, 0)
</style>